using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web;

namespace Common
{
	/// <summary>
	/// 规则约定：真实的Url参数必须是以下三种情况：
	/// Key=true
	/// Key=Int
	/// Lang=En
	/// 
	/// __pins 将会使Url不作转换。
	/// </summary>
	public static partial class HtmlTranslate
	{
		public static string ResolveToFullPath (string OriHtml)
		{
			string html = OriHtml;
			
			string other = "";
			int PreIndex = 0;
			
			//其实还要再加上一个限制, 不能在 value="" 里. 
			MatchCollection allMatch = Regex.Matches (html, @"(?<=<(a|link|img|script|input|form)[^>]*?(href|src|action)=(\""|'))[^\3]*?(?=\3[^>]*?>)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
			
			foreach (Match match in allMatch) {
				string url = match.Value;
				
				if (url.IndexOf ("~") != -1) {
					url = url.ResolveUrl ();
				}
				
				other += html.Substring (PreIndex, match.Index - PreIndex) + url;
				
				PreIndex = match.Index + match.Length;
			}
			
			html = other + html.Substring (PreIndex);
			
			{
				//解析 url 属性。
				//零宽断言(?=exp)  以及 零宽度正预测先行断言(?<=exp), 这种表达方式更牛。
				allMatch = Regex.Matches (html, @"(?<=\burl\s*\(('|"")?).*?(?=\))", RegexOptions.IgnoreCase);
				
				string[] eachString = Regex.Split (html, @"(?<=\burl\s*\(('|"")?).*?(?=\))", RegexOptions.IgnoreCase);
				
				for (int i = 1; i < eachString.Length; i++) 
				{
					if ( i % 2 == 1 )
					{
						string virPath = allMatch[(i-1)/2].Value  ;
						if ( virPath.StartsWith("~") )
						{
							eachString[i] = virPath.ResolveUrl() ;
						}
					}
				}
				html = string.Join ("", eachString);
			}
			
			{
				//解析 open, showModalDialog 属性。以及， Pop ， PopOpen
				//零宽断言(?=exp)  以及 零宽度正预测先行断言(?=exp)
				
				html = Regex.Replace (html, @"(?<=\b(Open|showModalDialog|Pop)\b\s*\(\s*('|\""|&quot;))~/(?=.*?\2\s*\))", "".GetUrlHeader (), RegexOptions.IgnoreCase | RegexOptions.Singleline);
			}
			
			return html;
		}
		
		public delegate string DeptUrlDelegate (string url);
		public static string ResolveToFullPath (string OriHtml, DeptUrlDelegate ProcDeptUrl)
		{
			string html = OriHtml;
			
			string other = "";
			int PreIndex = 0;
			
			//其实还要再加上一个限制, 不能在 value="" 里. 
			//MatchCollection allMatch = Regex.Matches (html, @"<(a|link|img|script|input|form)[^>]*?(href|src|action)=(\""|'|)([^\3]*?)\3[^>]*?>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
			MatchCollection allMatch = Regex.Matches (html, @"(?<=<(a|link|img|script|input|form)[^>]*?(href|src|action)=(\""|'))[^\3]*?(?=\3[^>]*?>)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
			
			foreach (Match match in allMatch) {
				string url = match.Value;
				
				if (url.IndexOf ("~") != -1) {
					url = url.ResolveUrl ();
				}
				
				if (ProcDeptUrl != null) {
					string mainurl = url.Split ('?')[0];

                    if (mainurl.EndsWith(".aspx") && Common.CmnProc.GetHtmlPropertyValue(match.Value, "__pins") != "true")
                    {
						if (url.ToLower ().StartsWith ("javascript:") == false && url.ToLower ().Contains ("&quot;") == false) {						
							url = ProcDeptUrl (url);
						}
					}
				}
				
				
				other += html.Substring (PreIndex, match.Index - PreIndex) + url;
				
				PreIndex = match.Index + match.Length;
				//html = html.Replace(match.Groups[match.Groups.Count - 2].Value, url);
			}
			
			html = other + html.Substring (PreIndex);
			
			{
				//解析 url 属性。
				//零宽断言(?=exp)  以及 零宽度正预测先行断言(?=exp), 这种表达方式更牛。
				allMatch = Regex.Matches (html, @"(?<=\burl\s*\(('|"")?).*?(?=\))", RegexOptions.IgnoreCase);
				
				string[] eachString = Regex.Split (html, @"(?<=\burl\s*\(('|"")?).*?(?=\))", RegexOptions.IgnoreCase);
				
				for (int i = 1; i < eachString.Length; i++) 
				{
					if ( i % 2 == 1 )
					{
						string virPath = allMatch[(i-1)/2].Value  ;
						if ( virPath.StartsWith("~") )
						{
							eachString[i] = virPath.ResolveUrl() ;
						}
					}
				}
				html = string.Join ("", eachString);
			}
			
			{
				//解析 open, showModalDialog 属性。以及， Pop ， PopOpen
				//零宽断言(?=exp)  以及 零宽度正预测先行断言(?=exp)
				
				html = Regex.Replace (html, @"(?<=\b(Open|showModalDialog|Pop)\b\s*\(\s*('|\""|&quot;))~/(?=.*?\2\s*\))", "".GetUrlHeader (), RegexOptions.IgnoreCase | RegexOptions.Singleline);
			}
			
			if (ScriptManager.GetCurrent (HttpContext.Current.CurrentHandler as Page) != null && ScriptManager.GetCurrent (HttpContext.Current.CurrentHandler as Page).IsInAsyncPostBack) {
				//把增量都算到第一个UpdatePanel 里,是不是有点不合理.
				int OffSetCharCount = html.Length - OriHtml.Length;
				string[] eachOne = html.Split ('|');
				eachOne[0] = (eachOne[0].GetInt () + OffSetCharCount).ToString ();
				
				html = string.Join ("|", eachOne);
			}
			
			//mono 执行这句会死掉。 死循环。 于新海。
			//html = Regex.Replace (html, "(\\b*__pinaspx=\".*?\"\\b*)|(\\b*__pins=\".*?\"\\b*)|(\\b*__tosysvar=\".*?\"\\b*)", "", RegexOptions.IgnoreCase);
			//html = Regex.Replace (html, "(\\b*__pinaspx=\".*?\"\\b*)|(\\b*__pins=\".*?\"\\b*)|(\\b*__tosysvar=\".*?\"\\b*)", "", RegexOptions.IgnoreCase);
			return html;
		}

		public delegate string TranslateASPXToHtml (string Url);

		 
		public static bool IsResourceUrl (string Url)
		{
			return Url.StartsWith ("~/WebResource.axd?d=".ResolveUrl ());
		} 
	}
}
